#include "datamodel.h"
#include "sqlitedb.h"
#include <QDebug>
typedef QVector<QString> itemData;
class ItemListModelPrivate
{
public:
    QHash<int, QByteArray> m_roleNames;
    QVector<itemData *> m_items;
    QString sql;
    QStringList columnNameList;

    ItemListModelPrivate()
    {
        int role = Qt::UserRole;
        m_roleNames.insert(role++, "code");
        m_roleNames.insert(role++, "title");
        m_roleNames.insert(role++, "time");
    }

    ~ItemListModelPrivate()
    {
        clear();
    }

    void InitalData()
    {
        qDebug() <<"那啥的列表"+ columnNameList.at(0);
        int role = Qt::UserRole;
        for(int i=0; i< columnNameList.length(); i++)
        {
            m_roleNames.insert(role++, columnNameList.at(i).toLatin1());
        }
    }

    void clear()
    {
        int count = m_items.size();
        if(count >0)
        {
            for(int i=0; i<count; i++)
            {
                delete m_items.at(i);
            }
            m_items.clear();
        }
    }

    void load()
    {
        qDebug() << "Sql语句是："+sql;
        itemData *item;
        SqliteDB *db = new SqliteDB();
        db->connectDB();
        db->query->prepare(sql);
        if(!db->query->exec())
        {
            qDebug() << sql  + " exec failed ! ";
        }
        else
        {
            while(db->query->next())
            {
                for(int i=0; i< db->query->size(); i++)
                {
                    item->append(db->query->value(i).toString());
                }

                m_items.append(item);
            }
        }
        db->closeDB();
    }
};


DataModel::DataModel(QObject *parent)
    : QAbstractListModel(parent)
    ,m_dptr(new ItemListModelPrivate())
{

}

DataModel::~DataModel()
{
    delete m_dptr;
}

//初始化形式数据
void DataModel::InitialData(QString sql, QStringList list){
    m_dptr->sql = sql;
    m_dptr->columnNameList = list;
    m_dptr->InitalData();
}

int DataModel::rowCount(const QModelIndex &parent) const
{
    return m_dptr->m_items.size();
}

QVariant DataModel::data(const QModelIndex &index, int role) const
{
   QVector<QString> *item = m_dptr->m_items[index.row()];
    return item->at(role - Qt::UserRole);
}

void DataModel::setSql(const QString &tbl)
{
    m_sql = tbl;
    m_dptr->sql =tbl;
    m_dptr->load();
}

QString DataModel::sql() const
{
    return m_sql;
}

void DataModel::setColumnNameList(const QStringList list)
{
    m_ColumnName = list;
   // m_dptr->InitalData();
}

QStringList DataModel::columnNameList() const
{
    return m_ColumnName;
}

QHash<int, QByteArray> DataModel::roleNames() const
{
    return m_dptr->m_roleNames;
}
